//
//  ViewController.m
//  03-折叠图片
//
//  Created by J on 16/2/27.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *top;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIImageView *middle;

@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic)  CAGradientLayer *gradient;

@end

@implementation ViewController
//一张图片分2个控件展示,旋转的时候,只旋转上部分控件
//如何让一张完整的图片通过2个控件显示
//通过layer 控制一个图片的显示内容
//如果快速地把两个控件拼接成一个完整的图片
- (void)viewDidLoad {
    [super viewDidLoad];
    //设置显示范围
//    self.imageView.layer.contentsRect = CGRectMake(0, 0, 1, 0.5);

    self.top.layer.contentsRect = CGRectMake(0, 0, 1, 0.5);
    self.top.layer.anchorPoint = CGPointMake(0.5, 1);
    
    self.middle.layer.contentsRect = CGRectMake(0, 0.5, 1, 0.5);
    self.middle.layer.anchorPoint = CGPointMake(0.5, 0);

    
    //添加手势
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self.bgView addGestureRecognizer:pan];
    
    
    //渐变图层
    CAGradientLayer * gradient = [CAGradientLayer layer];
    gradient.frame = self.middle.layer.bounds;//注意图层需要设置尺寸
    gradient.colors = @[(id)[UIColor clearColor].CGColor,(id)[UIColor blackColor].CGColor];
    [self.middle.layer addSublayer:gradient];
    gradient.opacity = 0;
    self.gradient = gradient;

}

//拖动的时候选装上部分内容 200 M_PI
- (void)pan:(UIPanGestureRecognizer*)pan{
    
    //获取偏移量 往下逆时针选装
    CGPoint transP = [pan translationInView:_bgView];
    //旋转角度
    
    CGFloat angle = -transP.y / 200.0*M_PI;//y增大逆时针
    CATransform3D transForm = CATransform3DMakeRotation(angle, 1, 0, 0);
    //增加旋转立体感 近大远小  500.0距离图层的距离

    transForm.m34 = -1/500.0;
    _top.layer.transform = transForm;
    
    self.gradient.opacity = transP.y * 1/200.0;
    //设置阴影效果
    
    //usingSpringWithDamping数值越小弹簧效果越明显
    //Velocity初始速度
    if (pan.state == UIGestureRecognizerStateEnded) {
        [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            _top.layer.transform = CATransform3DIdentity;
            self.gradient.opacity = 0;

        } completion:^(BOOL finished) {
            
        }];


    }
    
    
    
    
}

@end
